package com.isky.visual.user.controller;


import com.isky.visual.constant.CommonConstant;
import com.isky.visual.feign.BigDataIdsFeign;
import com.isky.visual.interceptor.annotation.LoginValidate;
import com.isky.visual.redis.RedisService;
import com.isky.visual.redis.UserKey;
import com.isky.visual.result.CodeMsg;
import com.isky.visual.result.ResultVo;
import com.isky.visual.user.entity.User;
import com.isky.visual.user.service.IuserService;
import com.isky.visual.user.vo.LoginVo;
import com.isky.visual.user.vo.UnifiedVisualResult;
import com.isky.visual.user.vo.UserInfoTreeVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.*;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author wudl
 * @since 2020-04-15
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = {"用户相关接口"})
public class UserController {

    @Autowired
    IuserService iuserService;

    @Autowired
    BigDataIdsFeign bigDataIdsFeign;

    @Autowired
    RedisService redisTemplate;

    @Autowired
    RestTemplate restTemplate;

    @Value("${user.verify.service}")
    private String userVerifySerivice;

    @GetMapping(value = "/getAllUser")
    @ApiOperation("获取所有用户")
    public ResultVo<List<User>> getAllUser() {
        return iuserService.getUser();
    }

    @LoginValidate(false)
    @PostMapping(value = "/login")
    @ApiOperation("登录接口")
    public ResultVo<String> loginUser(HttpServletRequest request, @RequestBody @ApiParam("登录参数实体") LoginVo loginVo) {

        String url = String.format("http://%s/user/loginVisualloginUser",userVerifySerivice);
        Map<String,String> visualParam = new HashMap<>();
        visualParam.put("username",loginVo.getUsername());
        visualParam.put("password",loginVo.getPassword());
        ResponseEntity<ResultVo<List<UnifiedVisualResult>>> exchange = this.restTemplate.exchange(url, HttpMethod.POST,
                new HttpEntity<>(visualParam),
                new ParameterizedTypeReference<ResultVo<List<UnifiedVisualResult>>>() {
                });
        ResultVo<List<UnifiedVisualResult>> body = exchange.getBody();
        if(body == null){
            return ResultVo.error(CodeMsg.LOGIN_FAILD);
        }

        if(Objects.equals(body.getCode(),100) && body.getData() != null){
            List<UnifiedVisualResult> data = body.getData();
            if(data!= null && !data.isEmpty()){
                User user = null;
                for(UnifiedVisualResult visual : data){
                    user = iuserService.supplement(visual);
                }
                request.getSession().setAttribute(CommonConstant.USER_SESSION_ID, user);
                return ResultVo.success(CodeMsg.LOGIN_SUCCESS.getMsg());
            }
        }else if(!Objects.equals(body.getCode(),100)){
            ResultVo.error(-1,body.getMsg());
        }

        return ResultVo.error(CodeMsg.LOGIN_FAILD);
    }

//    @PostMapping("/test")
//    @LoginValidate(false)
//    public ResultVo getLoginResult(@RequestBody Map<String, Object> queryMap) {
//        return ResultVo.success(bigDataIdsFeign.getLoginResult(queryMap));
//    }


    @PostMapping("/groupInfoTree")
    public ResultVo<List<UserInfoTreeVO>> groupInfoTree() {
        try{
            String url = String.format("http://%s/visual/getUserAllGroup",userVerifySerivice);
            ResponseEntity<ResultVo<List<UnifiedVisualResult>>> exchange = this.restTemplate.exchange(url, HttpMethod.GET,
                    new HttpEntity<>(null),
                    new ParameterizedTypeReference<ResultVo<List<UnifiedVisualResult>>>() {
                    });
            ResultVo<List<UnifiedVisualResult>> body = exchange.getBody();

            if(body != null && Objects.equals(body.getCode(),100) && body.getData() != null){
                List<UnifiedVisualResult> data = body.getData();
                if(data!= null && !data.isEmpty()){
                    User user = null;
                    for(UnifiedVisualResult visual : data){
                        user = iuserService.supplement(visual);
                    }
                }
            }
        }catch (Exception e){
            log.error("groupInfoTree->{}", e);
        }

        List<UserInfoTreeVO> userInfoTreeVOS = iuserService.groupTreeInfo();
        if(userInfoTreeVOS == null){
            userInfoTreeVOS = new ArrayList<UserInfoTreeVO>();
        }
        return ResultVo.success(userInfoTreeVOS);
    }

    @ApiOperation("删除用户组")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户组id", required= true,dataType = "Long", paramType = "query")
    })
    @PostMapping("/deleteGroup")
    public ResultVo<String> deleteGroup(Long id) {
        boolean delete = iuserService.deleteGroup(id);
        return delete ? ResultVo.success() : ResultVo.error();
    }

}
